package com.buffered.exam;

import java.io.*;

/**
 * @author げっしょく
 * @date 2021/8/1
 */
public class Demo5 {
    static byte[] bytes = new byte[1024];
    static int len = 0;

    public static void main(String[] args) throws IOException {
        File f = new File("D:\\itheima\\资料\\JavaSE\\JavaSE每日作业");
//        FileInputStream fis = new FileInputStream("D:\\Git");
        File f2 = new File("C:\\");
        copeFile(f, f2);
    }

    private static void copeFile(File f, File f2) {
        if (f.isDirectory()) {
            String s = f.getAbsolutePath();
            String temp = (f2.getAbsolutePath().endsWith("\\") ? f2.getAbsolutePath() : f2.getAbsolutePath() + "\\") + s.substring(3);
            File f3 = new File(temp);
        }
        File[] files = f.listFiles();
        if (files != null) {
            for (File file : files) {
                if (!file.isFile()) {
                    String gap = file.getAbsolutePath();
                    String temp = (f2.getAbsolutePath().endsWith("\\") ? f2.getAbsolutePath() : f2.getAbsolutePath() + "\\") + gap.substring(3);
                    File f1 = new File(temp);
                    f1.mkdirs();
                    copeFile(file, f2);
                } else {
                    String gap = file.getAbsolutePath();
                    FileInputStream fis = null;
                    FileOutputStream fos = null;
                    try {
                        fis = new FileInputStream(gap);
                        String temp = (f2.getAbsolutePath().endsWith("\\") ? f2.getAbsolutePath() : f2.getAbsolutePath() + "\\") + gap.substring(3);
                        fos = new FileOutputStream(temp);
                        while ((len = fis.read(bytes)) != -1) {
                            fos.write(bytes);
                        }
                        fos.flush();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fis != null) {
                            try {
                                fis.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (fos != null) {
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}
